package utils.db.impl;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pojo.Device;
import pojo.EUserType;
import pojo.User;
import tools.Translator;
import utils.db.api.ISearch;
import utils.db.mapper.IMapper;
import utils.db.mapper.Mapper;

public class Search extends DBOperation implements ISearch {
	private static Logger logger = LoggerFactory.getLogger(Search.class);
	private IMapper mapper = new Mapper();

	@Override
	public List<Device> searchDevices(String search, EUserType type,
			int clientId) {
		List<Device> devices = new ArrayList<Device>();
		if (type.name().equals("CLIENT") ) {
			try {
				pstmt = getConnector().prepareStatement(SEARCH_DEVICE_CLIENT);

				pstmt.setString(1, search);
				pstmt.setString(2, Translator.toEnglish(search));
				pstmt.setString(3,Translator.toEnglish(search));
				pstmt.setInt(4, clientId);
				rs = pstmt.executeQuery();
				devices = mapper.devicesMapp(rs);
				pstmt.close();
			} catch (SQLException e) {
				logger.error("Error during search device client");
			}
		} else if(type.name().equals("ADMIN")){
			try {
				pstmt = getConnector().prepareStatement(SEARCH_DEVICE_ADMIN);

				pstmt.setString(1, search);
				pstmt.setString(2, Translator.toEnglish(search));
				pstmt.setString(3, Translator.toEnglish(search));
				rs = pstmt.executeQuery();
				devices = mapper.devicesMapp(rs);

				pstmt.close();
			} catch (SQLException e) {
				logger.error("Error during search device admin");
			}
		}else{
			try {
				pstmt = getConnector().prepareStatement(SEARCH_DEVICE_SERVICEMAN);

				pstmt.setString(1, search);
				pstmt.setString(2, Translator.toEnglish(search));
				pstmt.setString(3, Translator.toEnglish(search));
				rs = pstmt.executeQuery();
				devices = mapper.devicesMapp(rs);

				pstmt.close();
			} catch (SQLException e) {
				logger.error("Error during search device serviceman");
			}
		}
		return devices;

	}

	@Override
	public List<User> searchUsers(String search) {
		List<User> users = new ArrayList<User>();

		try {
			pstmt = getConnector().prepareStatement(SEARCH_USER);
			pstmt.setString(1, search);
			pstmt.setString(2, search);
			pstmt.setString(3, search);
			pstmt.setString(4, search);
			pstmt.setString(5, search);
			rs = pstmt.executeQuery();
			users = mapper.usersMapp(rs);
			pstmt.close();

		} catch (SQLException e) {
			System.out.println(e.getStackTrace());
			logger.error("Error during search user. Query: " + pstmt.toString());
		}

		return users;
	}

	public static void main(String[] args) {
		Search dfetcher = new Search();
		// dfetcher.searchUsers("Wojciech");

		System.out.println(dfetcher.searchDevices("Laptop", EUserType.CLIENT,
				11));
	}
}
